package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 */
public class Client {
    private Socket socket;

    public Client(){
        try {
            System.out.println("正在连接服务端。。。");
            socket = new Socket("176.225.210.21",8088);
            System.out.println("与服务端建立连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {

            Thread t = new Thread(new ServerHandler());
            t.setDaemon(true);
            t.start();

            OutputStream ops = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(new BufferedWriter(
                             new OutputStreamWriter(ops, StandardCharsets.UTF_8)),true);

            Scanner scanner = new Scanner(System.in);

            System.out.println("开始输入内容：输入exit停止");

            while (true){

//                String line = scanner.nextLine();
                String str = "月影霜华";
//                if (line.equals("exit")){
//                    break;
//                }else{
//                    pw.println(line);
//                }
                while (true){
                    pw.println(str);
                }
            }

        } catch (IOException e) {
            System.out.println("客户端断开连接");
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端断开连接");
            }
        }
    }
    public static void main(String[] args){

        Client client = new Client();
        client.start();
    }
    private class ServerHandler implements Runnable{

        @Override
        public void run() {
            try {
                InputStream ips = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(ips, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String message ;
                while ((message = br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
